package com.csdj.springboottest.service;

import com.csdj.springboottest.common.CommonConstant;
import com.csdj.springboottest.entity.User;
import com.csdj.springboottest.mapper.UserMapper;
import com.csdj.springboottest.util.EncryptUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * author:cloud
 * date:2021/4/21 0021
 **/

@Service
public class UserService {

    @Resource
    private RedisService redisService;

    @Resource
    private UserMapper userMapper;

    public List<User> getAll(){
        return userMapper.findAll();
    }

    /**
     * 查询用户详情
     * @param id
     * @return
     */
    public User get(int id){
        //先查询缓存
        Object o = redisService.get("cache_user_" + String.valueOf(id));
        if(o == null){
            //缓存中不存在数据
            User user = userMapper.findById(id);
            if(user == null){
                return null;
            }
            //把数据保存到缓存中，方便下次查询
            redisService.set("cache_user_"+String.valueOf(user.getId()),user,3600);
            return user;
        }
        return (User)o;
    }

    public boolean update(User user){
        int res = userMapper.update(user);
        if(res >0){
            redisService.delKey("cache_user_"+String.valueOf(user.getId()));
        }
        return res >0;
    }

    public User getByUsername(String username){
        return userMapper.findByUsername(username);
    }




    public User login(String username,String password,String token){
        String depass = EncryptUtil.getMd5(password);
        User user = userMapper.login(username,depass);
        if(user == null)return null;
        redisService.set(CommonConstant.CACHE_TOKEN_PREFIX+user.getId(),token,CommonConstant.CACHE_TOKEN_DURING_SECOND);
        return user;
    }
}
